package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import com.conversationboard.batch.scheduler.Jobs;
import com.conversationboard.config.Configuration;
import com.conversationboard.model.User;

@WebServlet(name = "AdminTriggerBatchJobControllerServlet", urlPatterns = "/Admin/AdminTriggerBatchJobControllerServlet")
public class AdminTriggerBatchJobControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 2316531412865658333L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if ((!user.isSiteAdmin()) || (!SecurityChecks.passes(request, user, this))) {
				return;
			}

			Scheduler scheduler = Jobs.getScheduler();

			String jobName = request.getParameter("jobName");
			String groupName = request.getParameter("groupName");

			boolean wasInStandbyMode = scheduler.isInStandbyMode();

			if (wasInStandbyMode) {
				scheduler.start();
			}

			scheduler.triggerJobWithVolatileTrigger(jobName, groupName);

			if (wasInStandbyMode) {
				scheduler.standby();
			}

			response.sendRedirect(Configuration.getInstance().getRoot() + "/Admin/AdminBatchJobStatusControllerServlet");

		} catch (SchedulerException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
